package com.example.site.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.site.entity.User;
import com.example.site.enums.RuleEnum;
import com.example.site.enums.SexEnum;
import com.example.site.enums.StatusEnum;
import com.example.site.service.UserService;
import com.example.site.mapper.UserMapper;
import com.example.site.util.PasswordUtil;
import com.example.site.vo.PageVO;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * @author haoka
 * @description 针对表【hotel_user】的数据库操作Service实现
 * @createDate 2023-04-11 13:52:20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    /**
     * @param username
     * @param password
     * @return
     * @deprecated 登录
     */
    public SaResult login(String username, String password) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username).eq(User::getPassword, PasswordUtil.encryptPassword(password));
        User user = this.getOne(queryWrapper);
        if (user == null) {
            return SaResult.error("用户名或密码错误");
        }

        StpUtil.login(user.getId());

        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return SaResult.data(tokenInfo);
    }

    /**
     * @return
     * @deprecated 获取当前用户的 userinfo
     */
    public SaResult fetchUserinfo() {
        User user = this.getById(StpUtil.getLoginIdAsInt());
        if (user == null) {
            return SaResult.error("该用户已在系统注销");
        } else {
            return SaResult.data(user);
        }
    }

    /**
     * @param data
     * @return
     * @deprecated 用户注册
     */
    public SaResult createUser(Map<String, String> data) {
        String username = data.get("username");
        String name = data.get("name");
        String phone = data.get("phone");
        String password = data.get("password");
        String checkPassword = data.get("checkPassword");
        String sex = data.get("sex");
        if (StringUtils.isNotBlank(username)) {
            if (username.length() < 1 || username.length() > 30) {
                return SaResult.error("账号限制在1~30个字符");
            } else {
                if (StringUtils.isNotBlank(password) && StringUtils.isNotBlank(checkPassword)) {
                    if (password.equals(checkPassword)) {
                        User user = new User();
                        user.setUsername(username);
                        user.setPassword(PasswordUtil.encryptPassword(password));
                        user.setSex(SexEnum.valueOf(sex));
                        user.setRule(RuleEnum.USER);
                        user.setName(name);
                        user.setPhone(phone);
                        user.setStatus(StatusEnum.NORMAL);
                        user.setRegisterTime(new Date());
                        try {
                            boolean user_result = this.save(user);
                            if (user_result) {
                                return SaResult.ok();
                            } else {
                                return SaResult.error("用户名已被使用");
                            }
                        } catch (DataAccessException e) {
                            return SaResult.error("用户名已被使用");
                        }
                    } else {
                        return SaResult.error("两次密码不一致");
                    }
                } else {
                    return SaResult.error("请输入密码");
                }
            }
        } else {
            return SaResult.error("请输入账号");
        }
    }


    /**
     * @param data
     * @return
     * @deprecated 用户注册
     */
    public SaResult sign(Map<String, String> data) {
        String username = data.get("username");
        String name = data.get("name");
        String phone = data.get("phone");
        String password = data.get("password");
        if (StringUtils.isNotBlank(username)) {
            if (username.length() < 1 || username.length() > 30) {
                return SaResult.error("账号限制在1~30个字符");
            } else {
                if (StringUtils.isNotBlank(password)) {
                    User user = new User();
                    user.setUsername(username);
                    user.setPassword(PasswordUtil.encryptPassword(password));
                    user.setSex(SexEnum.MALE);
                    user.setRule(RuleEnum.USER);
                    user.setName(name);
                    user.setPhone(phone);
                    user.setStatus(StatusEnum.NORMAL);
                    user.setRegisterTime(new Date());
                    try {
                        boolean user_result = this.save(user);
                        if (user_result) {
                            return SaResult.ok();
                        } else {
                            return SaResult.error("用户名已被使用");
                        }
                    } catch (DataAccessException e) {
                        return SaResult.error("用户名已被使用");
                    }

                } else {
                    return SaResult.error("请输入密码");
                }
            }
        } else {
            return SaResult.error("请输入账号");
        }
    }

    /**
     * @param data
     * @return
     * @deprecated 创建前台用户
     */
    public SaResult createFrontUser(Map<String, String> data) {
        String username = data.get("username");
        String name = data.get("name");
        String phone = data.get("phone");
        String password = data.get("password");
        String sex = data.get("sex");
        if (StringUtils.isNotBlank(username)) {
            if (username.length() < 1 || username.length() > 30) {
                return SaResult.error("账号限制在1~30个字符");
            } else {
                if (StringUtils.isNotBlank(password)) {
                    User user = new User();
                    user.setUsername(username);
                    user.setPassword(PasswordUtil.encryptPassword(password));
                    user.setSex(SexEnum.valueOf(sex));
                    user.setRule(RuleEnum.FRONT_USER);
                    user.setName(name);
                    user.setPhone(phone);
                    user.setStatus(StatusEnum.NORMAL);
                    user.setRegisterTime(new Date());
                    try {
                        boolean user_result = this.save(user);
                        if (user_result) {
                            return SaResult.ok();
                        } else {
                            return SaResult.error("用户名已被使用");
                        }
                    } catch (DataAccessException e) {
                        return SaResult.error("用户名已被使用");
                    }

                } else {
                    return SaResult.error("请输入密码");
                }
            }
        } else {
            return SaResult.error("请输入账号");
        }
    }

    /**
     * @param data
     * @return
     * @deprecated 修改密码
     */
    public SaResult changePassword(Map<String, String> data) {
        String oldPassword = data.get("oldPassword");  // 获取旧密码
        String newPassword = data.get("newPassword");  // 获取新密码
        String checkPassword = data.get("checkPassword");  // 获取确认密码

        if (StringUtils.isNotBlank(newPassword) && newPassword.length() >= 6) {  // 判断新密码是否为空且长度不小于6位
            if (StringUtils.isNotBlank(checkPassword) && checkPassword.equals(newPassword)) {  // 判断确认密码是否与新密码相同
                User user = this.getById(StpUtil.getLoginIdAsInt());  // 获取当前用户对象
                if (user.getPassword().equals(PasswordUtil.encryptPassword(oldPassword))) {  // 判断旧密码是否正确
                    user.setPassword(PasswordUtil.encryptPassword(newPassword));  // 更新用户密码
                    this.updateById(user);  // 更新用户信息到数据库
                    return SaResult.ok("修改密码成功");  // 返回成功结果
                } else {
                    return SaResult.error("原密码不正确");  // 返回错误结果：原密码不正确
                }
            } else {
                return SaResult.error("两次密码不一致");  // 返回错误结果：两次密码不一致
            }
        } else {
            return SaResult.error("密码长度不可小于6位");  // 返回错误结果：密码长度不足6位
        }
    }

    /**
     * @param data
     * @return
     * @deprecated 修改信息
     */
    public SaResult editUserinfo(Map<String, String> data) {
        User user = this.getById(StpUtil.getLoginIdAsInt());

        String sex = data.get("sex");
        String name = data.get("name");
        String phone = data.get("phone");
        try {
            user.setSex(SexEnum.valueOf(sex));
            user.setName(name);
            user.setPhone(phone);
            this.updateById(user);
            return SaResult.ok();
        } catch (DataAccessException e) {
            return SaResult.error("修改失败");
        }
    }

    /**
     * @param data
     * @return
     * @deprecated 管理员修改前台用户信息
     */
    public SaResult adminEditUserinfo(Map<String, String> data) {
        String id = data.get("id");

        String sex = data.get("sex");
        String name = data.get("name");
        String phone = data.get("phone");
        try {
            User user = this.getById(id);
            user.setSex(SexEnum.valueOf(sex));
            user.setName(name);
            user.setPhone(phone);
            this.updateById(user);
            return SaResult.ok();
        } catch (DataAccessException e) {
            return SaResult.error("修改失败");
        }
    }

    /**
     * @param data
     * @return
     * @deprecated 获取用户列表
     */
    public SaResult getList(Map<String, String> data) {
        String name = data.get("name");
        String rule = data.get("rule");
        String username = data.get("username");

        String _page = data.getOrDefault("page", "1");
        String _page_size = data.getOrDefault("page_size", "20");
        Page<User> page = new Page<>(Integer.parseInt(_page), Integer.parseInt(_page_size));

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like(User::getName, name);
        }

        if (StringUtils.isNotBlank(rule)) {
            queryWrapper.eq(User::getRule, RuleEnum.valueOf(rule));
        }

        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like(User::getUsername, username);
        }

        this.page(page, queryWrapper);

        PageVO<User> pageVO = new PageVO<>(page);

        return SaResult.data(pageVO);
    }

}




